//
//  OAuthViewController.swift
//  VVbo
//
//  Created by Mr.Run on 2017/8/24.
//  Copyright © 2017年 Mr.Run. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
        view.backgroundColor = UIColor.white
        webView.scrollView.isScrollEnabled = false
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 16, target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 16, target: self, action: #selector(autoFill), isBack: false)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(RedirectURI)"
        
        guard let url = URL(string:urlString) else {
            return
        }
        let request = URLRequest(url: url)
        webView.loadRequest(request)
    }
    
    @objc fileprivate func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoFill() {
        let js = "document.getElementById('userId').value='mingzixi@sina.cn';" + "document.getElementById('passwd').value='********'"
        
        webView.stringByEvaluatingJavaScript(from: js)
    }
}

extension OAuthViewController: UIWebViewDelegate {
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if request.url?.absoluteString.hasPrefix(RedirectURI) == false {
            return true
        }
        
        if request.url?.query?.hasPrefix("code=") == false {
            close()
            return false
        }
        
//        print("加载请求  ------  \(request.url?.query ?? "")")
//        print("加载请求  ------  \(request.url?.absoluteString ?? "")")
        
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print("授权码------\(code)")
        
        NetworkManager.shared().loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess{
                SVProgressHUD.show(withStatus: "网络请求失败")
            }else{
//                SVProgressHUD.show(withStatus: "登录成功")
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: UserloginSuccessNotification), object: nil)
                self.close()
            }
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
